package com.member.web.controller.shop;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.member.common.annotation.Log;
import com.member.common.constant.HttpStatus;
import com.member.common.core.controller.BaseController;
import com.member.common.core.domain.AjaxResult;
import com.member.common.core.page.TableDataInfo;
import com.member.common.enums.BizUserStatusEnum;
import com.member.common.enums.BusinessType;
import com.member.common.utils.fy.HttpUtil;
import com.member.common.utils.fy.SignatureUtils;
import com.member.common.utils.poi.ExcelUtil;
import com.member.common.utils.uuid.IdUtils;
import com.member.shop.domain.SpecsSku;
import com.member.shop.domain.SpecsSkuItemData;
import com.member.shop.domain.SysBizGoodsSku;
import com.member.shop.dto.ExternalGoodsSkuDto;
import com.member.shop.service.ISysBizGoodsSkuService;
import com.member.shop.vo.ExternalGoodsSkuVo;
import com.member.web.controller.tool.SpecAlgorithm;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【商品sku】控制器
 *
 * @author lixinchen
 * @version 1.0
 * @date 2024-01-05
 **/
@RestController
@RequestMapping("/shop/sku")
public class SysBizGoodsSkuController extends BaseController {
    @Resource
    private ISysBizGoodsSkuService sysBizGoodsSkuService;

    @Value("${mall.order.productUrl}")
    private String productUrl;

    @Value("${mall.order.privateKey}")
    private String privateKey;


    private void setTenantId(SysBizGoodsSku sysBizGoodsSku) {
        Long tenantId = getTenantId();
        if (tenantId != null && tenantId > 0) {
            sysBizGoodsSku.setTenantId(tenantId);
        }
    }

    /**
     * 查询商品sku列表
     */
    @PreAuthorize("@ss.hasPermi('shop:sku:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysBizGoodsSku sysBizGoodsSku) {
        startPage();
        setTenantId(sysBizGoodsSku);
        LambdaQueryWrapper<SysBizGoodsSku> queryWrapper = new LambdaQueryWrapper<SysBizGoodsSku>();
        Long tenantId = getTenantId();
        if (tenantId != null && tenantId > 0) {
            queryWrapper.eq(SysBizGoodsSku::getTenantId, tenantId);
        }
        queryWrapper.eq(sysBizGoodsSku.getGoodsId() != null, SysBizGoodsSku::getGoodsId, sysBizGoodsSku.getGoodsId());
        List<SysBizGoodsSku> list = sysBizGoodsSkuService.selectSysBizGoodsSkuList(queryWrapper);
        return getDataTable(list);
    }


    /**
     * 查询商品sku列表
     */
    @PreAuthorize("@ss.hasPermi('shop:sku:list')")
    @GetMapping("/external/list")
    public TableDataInfo list(ExternalGoodsSkuDto externalGoodsSkuDto) {
        try {
            // 时间戳
            String timeStamp = String.valueOf(System.currentTimeMillis());

            // 签名（假设使用 SHA-256 对 data 和 timeStamp 进行签名）
            String sign = SignatureUtils.signWithSHA1(JSON.toJSONString(externalGoodsSkuDto), SignatureUtils.getPrivateKey(privateKey));

            // 请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("timeStamp", timeStamp);
            requestBody.put("sign", sign);
            requestBody.put("data", JSON.toJSONString(externalGoodsSkuDto));

            // 发送 POST 请求
            String response = HttpUtil.postJson(productUrl, JSON.toJSONString(requestBody));
            // 解析响应
            JSONObject jsonResponse = JSON.parseObject(response);

            // 检查 data 是否存在且为 JSONObject
            if (jsonResponse.containsKey("data") && jsonResponse.getJSONObject("data") != null) {
                JSONObject data = jsonResponse.getJSONObject("data");

                // 检查 row 是否存在且为 JSONArray 或其他期望类型
                if (data.containsKey("rows") && data.getJSONArray("rows") != null) {
                    JSONArray rows = data.getJSONArray("rows");
                    List<ExternalGoodsSkuVo> list = JSON.parseArray(rows.toJSONString(), ExternalGoodsSkuVo.class);
                    // 继续处理 rows 数据
                    TableDataInfo rspData = new TableDataInfo();
                    rspData.setCode(HttpStatus.SUCCESS);
                    rspData.setMsg("查询成功");
                    rspData.setRows(list);
                    rspData.setTotal(data.getLongValue("total"));
                    return rspData;
                } else {
                    // 处理 "row" 键不存在或类型不匹配的情况
                    return getDataTable(null);
                }
            } else {
                // 处理 "data" 键不存在或类型不匹配的情况
                return getDataTable(null);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
        return getDataTable(null);
    }


    /**
     * 刷新规格
     */
    @PreAuthorize("@ss.hasPermi('goods:specs:list')")
    @PostMapping("/specAlgorithm")
    public ArrayList<SysBizGoodsSku> specAlgorithm(@RequestBody SpecsSku specsSku) {

        List<List<String>> result = null;
        SpecAlgorithm<String> stringSpecAlgorithm = new SpecAlgorithm<>();


        List<SpecsSkuItemData> specs = specsSku.getSpecs();
        List<List<String>> lists = new ArrayList<>();
        for (int i = 0; i < specs.size(); i++) {
            SpecsSkuItemData specsData = specs.get(i);
            List<String> childs = specsData.getSelects();
            lists.add(childs);
        }
        if (specs.size() == 1) {
            result = stringSpecAlgorithm.specesPlan(lists.get(0));
        } else if (specs.size() == 2) {
            result = stringSpecAlgorithm.specesPlan(lists.get(0), lists.get(1));
        } else if (specs.size() == 3) {
            result = stringSpecAlgorithm.specesPlan(lists.get(0), lists.get(1), lists.get(2));
        } else if (specs.size() == 4) {
            result = stringSpecAlgorithm.specesPlan(lists.get(0), lists.get(1), lists.get(2), lists.get(3));
        } else if (specs.size() == 5) {
            result = stringSpecAlgorithm.specesPlan(lists.get(0), lists.get(1), lists.get(2), lists.get(3), lists.get(4));
        }

        ArrayList<SysBizGoodsSku> skuResults = new ArrayList<>();
        HashMap<String, SysBizGoodsSku> cache = new HashMap<>();


        if (result != null) {
            for (List<String> strings : result) {
                String skuCode = String.join(",", strings);
                SysBizGoodsSku sysBizGoodsSku = null;
                if (specsSku.getGoodsId() != null && specsSku.getGoodsId() != 0) {
                    sysBizGoodsSku = sysBizGoodsSkuService.selectSysBizGoodsSkuByGoodsIdAndKey(specsSku.getGoodsId(), skuCode);
                }
                if (sysBizGoodsSku == null) {
                    sysBizGoodsSku = new SysBizGoodsSku();
                    sysBizGoodsSku.setSpecsKey(skuCode);
                    sysBizGoodsSku.setSkuCode(skuCode);
                    sysBizGoodsSku.setPic(specsSku.getCover());
//                    sysBizGoodsSku.setStatus(1);
                    sysBizGoodsSku.setStock(0L);
//                    sysBizGoodsSku.setPrice(BigDecimal.ZERO);
//                    sysBizGoodsSku.setSalesPrice(BigDecimal.ZERO);
                    sysBizGoodsSku.setWeight(0L);
                    sysBizGoodsSku.setStatus(BizUserStatusEnum.OK.getKey());
                }

                cache.remove(skuCode);
                skuResults.add(sysBizGoodsSku);
            }
        }

        for (Map.Entry<String, SysBizGoodsSku> stringSysBizGoodsSkuEntry : cache.entrySet()) {

            skuResults.add(stringSysBizGoodsSkuEntry.getValue());
        }
        if (skuResults.size() > 0) {
            for (SysBizGoodsSku skuResult : skuResults) {
                skuResult.setSkuCode(IdUtils.fastSimpleUUID());
            }
        }
        return skuResults;
    }

    /**
     * 导出商品sku列表
     */
    @PreAuthorize("@ss.hasPermi('shop:sku:export')")
    @Log(title = "商品sku", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysBizGoodsSku sysBizGoodsSku) {
        LambdaQueryWrapper<SysBizGoodsSku> queryWrapper = new LambdaQueryWrapper<SysBizGoodsSku>();
        Long tenantId = getTenantId();
        if (tenantId != null && tenantId > 0) {
            queryWrapper.eq(SysBizGoodsSku::getTenantId, tenantId);
        }
        queryWrapper.eq(sysBizGoodsSku.getGoodsId() != null, SysBizGoodsSku::getGoodsId, sysBizGoodsSku.getGoodsId());

        List<SysBizGoodsSku> list = sysBizGoodsSkuService.selectSysBizGoodsSkuList(queryWrapper);
        ExcelUtil<SysBizGoodsSku> util = new ExcelUtil<SysBizGoodsSku>(SysBizGoodsSku.class);
        util.exportExcel(response, list, "商品sku数据");
    }

    /**
     * 获取商品sku详细信息
     */
    @PreAuthorize("@ss.hasPermi('shop:sku:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(sysBizGoodsSkuService.selectSysBizGoodsSkuById(id));
    }

    /**
     * 新增商品sku
     */
    @PreAuthorize("@ss.hasPermi('shop:sku:add')")
    @Log(title = "商品sku", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysBizGoodsSku sysBizGoodsSku) {
        return toAjax(sysBizGoodsSkuService.insertSysBizGoodsSku(sysBizGoodsSku));
    }

    /**
     * 修改商品sku
     */
    @PreAuthorize("@ss.hasPermi('shop:sku:edit')")
    @Log(title = "商品sku", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysBizGoodsSku sysBizGoodsSku) {
        return toAjax(sysBizGoodsSkuService.updateSysBizGoodsSku(sysBizGoodsSku));
    }

    /**
     * 删除商品sku
     */
    @PreAuthorize("@ss.hasPermi('shop:sku:remove')")
    @Log(title = "商品sku", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(sysBizGoodsSkuService.deleteSysBizGoodsSkuByIds(ids));
    }
}
